package cn.joker.springsecurity.config;

import cn.joker.springsecurity.handle.MyAccessDeniedHandler;
import cn.joker.springsecurity.handle.MyAuthenticationFailureHandler;
import cn.joker.springsecurity.handle.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author : jwp
 * @description :
 * @createDate : 2025/2/8 10:32
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public MyAccessDeniedHandler myAccessDeniedHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //表单提交
       http.formLogin()
               //自定义登录表单的提交路径
               .loginProcessingUrl("/login")
               //自定义登录页面
               .loginPage("/login.html")
               //登录成功之后跳转的路径,Post请求（和下面handler 冲突）
//               .successForwardUrl("/toMain")
               .successHandler(new MyAuthenticationSuccessHandler("/main.html"))
               //登录失败之后跳转的路径,Post请求
//               .failureForwardUrl("/toError")
               .failureHandler(new MyAuthenticationFailureHandler("/toError"))

               .usernameParameter("username")
               .passwordParameter("password");

       //授权配置
       http.authorizeRequests()
               .antMatchers("/error.html").permitAll()
//               .antMatchers("/error.html").access("permitAll()") //和尚庙同样作用
               .antMatchers("/login.html").permitAll()
//               .antMatchers("/images/**").permitAll()
               //正则表达式
//               .regexMatchers(".+[.]png").permitAll()
//               .regexMatchers(HttpMethod.GET,"/demo").permitAll()

//               .mvcMatchers("/demo").servletPath("/api").permitAll()
              //权限限制
               .antMatchers("/main.html").hasAnyAuthority("admin")

               //ip限制
//               .antMatchers("/main.html").hasIpAddress("127.0.0.1")

               //所有的请求都必须被认证，必须通过登录之后才可以访问
               .anyRequest().authenticated();

        //自定义权限实现
//                .anyRequest().access("@myServiceImpl.hasPermission(httpServletRequest,authentication)");


       //自定义403处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);


       //关闭csrf
       http.csrf().disable();
    }
}
